function P () {
	console.log.apply(console,arguments);
}

function getUrl( str ) {
	var arr = str.replace(/^\/|\/$/ ,"" ).split("/");
	if( arr.length == 2){
		return "?c=" + arr[0] + "&a=" + arr[1];
	} else {
		return "?c=" + arr[0];
	}
}	

//将文件大小转化成KB、MB、GB等
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};


function catTree(docs,catId){
	var tree = [];
	var cat_id = 'cat_id';
	catId = catId ? catId : '0';
	
	function cateTree(arr, _id ,level){		
		var item = null;
		var i = 0;
		_id = String(_id);
		for ( i in arr ) {
			item = arr[i];
			if ( item.parent_id.toString() ===  _id ){
				item.level = level;
				tree.push(item);
				tree.concat( arguments.callee(arr,item[cat_id],level+1) );
			}
		}

		return tree;
	}
	return cateTree(docs,catId,1);
};

function catRole(docs,roleId){
	var tree = [];
	var cat_id = 'id';
	roleId = roleId ? roleId : '0';
	
	function cateTree(arr, _id ,level){		
		var item = null;
		var i = 0;
		_id = String(_id);
		for ( i in arr ) {
			item = arr[i];
			if ( item.pid.toString() ===  _id ){
				item.level = level;
				tree.push(item);
				tree.concat( arguments.callee(arr,item[cat_id],level+1) );
			}
		}

		return tree;
	}
	return cateTree(docs,roleId,1);
};


/*
toal: 数据总条数
perpage: 每页几条
navLimit: 显示几个分页数字
page: 当前页
*/
function PageList( total, perpage, navLimit,page ){
	this.total = total;			//总记录数
	this.perpage = perpage;		//每页显示多少条记录
	this.count = 0;				//总页数
	this.navLimit = (undefined===navLimit) ? 10 : navLimit;	//当前页码数
	this.page = (undefined===page) ? 1 : page;	//当前页码数
	this.nav = [];
	this.skip = 0;		//用于数据库取记录的skip
	
}

PageList.prototype.reset = function(total,page){
	this.total = total;
	this.count = 0;
	this.page = page;
	this.nav = [];
	this.skip = 0;
	this.last = 0;
	this.first = 0;
}

PageList.prototype.prepare = function(page){
	if ( page!==undefined && page==this.page){
		return false;
	}
	this.page = parseInt(this.page);
	this.total = parseInt(this.total);
	this.nav = [];
	if( this.total<1 ){
		this.total = 0;
	}
	
	this.count = Math.ceil(this.total/this.perpage);
	
	//当前页是否大于总页数
	if( this.page >= this.count ){
		this.page = this.count;
	}
	
	//当前页是否小于1
	if( this.page <= 1 ){
		this.page = 1;
	}
	
	this.skip = ((this.page - 1) * this.perpage)  ;
	return this;
}

PageList.prototype.getSkip = function(){
	this.prepare();
	return this.skip;
}

PageList.prototype.list = function(){
	this.prepare();
	
	if ( this.total> 0 ) {
		this.nav.push(this.page);
	}	
	
	var left = this.page - 1;
	var right = this.page + 1;
	for(;(left>=1||right<=this.count) && this.nav.length<=this.total; ){
		if( this.nav.length>=this.navLimit){
			break;
		}
		
		if( left>=1 ){
			this.first = left;
			this.nav.unshift( left );
			left-=1;
		}
		if( right<=this.count ){
			this.last = right;
			this.nav.push( right );
			right+=1;
		}
		
	}

	return this.nav;
}




String.prototype.ucfirst = function(){
	return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}




//开发错误
console.devBug = function(){
	throw Error("开发错误");
};

//开发错误
var devBug = function(){
	throw Error("开发错误");
};

var app = angular.module('App', ['ngRoute','me-lazyload','ngImgCrop']);
app
//时间拦截器
.factory('timestampMarker', [function() {
	var dateStart = null;
    var timestampMarker = {
        request: function(config) {
			dateStart = new Date();
            return config;
        },
        response: function(response) {
			var arr = [];
			arr.push(response.config.method);	//GET、POST等	
			arr.push(response.config.url);	//url
			arr.push(response.status);	//状态码
			arr.push(response.statusText);	//状态文字
			arr.push((new Date()).getTime() - dateStart.getTime() + "ms");	
			console.log(arr.join(" "));
            return response;
        }
    };
    return timestampMarker;
}])
//保存拦截器
.factory('saveAjax', ['$location',function($location) {
    var saveAjax = {
        response: function(response) {
			if ( response.config.method=='PUT') {
					swal(
						{   
							title: "操作成功",   
							text: "按“确定”按钮返回",   
							type: "success",   
							//showCancelButton: true,
							//cancelButtonText: '取消',
							confirmButtonColor: "#DD6B55",   
							confirmButtonText: "确定",   
							closeOnConfirm: true
							//closeOnCancel: false
						});	
			}
            return response;
        },
		responseError: function(response) {
			if ( response.config.method=='PUT') {
				swal({
				title: "操作失败",
				text: response.statusText,
				type: "error",
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定",
				closeOnConfirm: true }
			);	
			}
            return response;
		}
    };
    return saveAjax;
}])
//请求的时候加遮罩层，返回的时候去掉遮罩层
.factory('requestOverlay', ['$location',function($location) {
	var overlay = document.querySelector("#request-overlay");
    var requestOverlay = {
        request: function(config) {
			overlay.style.display = "block";
			return config;
        },
		requestError: function(config) {
			overlay.style.display = "none";
			return config;			
		},
        response: function(response) {			
			overlay.style.display = "none";
			return response;
        },
		responseError: function(response) {
			
			overlay.style.display = "none";
			return response;			
		}
    };
    return requestOverlay;
}])
/*
有时候，我们的单页面应用中，会发生丢失 session 情况。这种情况可能由于 session 过期了或者服务器异常。我们来创建一个拦截器，用于恢复 session 然后自动重新发送原始请求(假设 session 过期的情况)。

为了演示目的，我们来假设发生了 session 过期返回 http 状态码 419。
*/
.factory('sessionRecoverer', ['$q', '$injector', function($q, $injector) {
    var sessionRecoverer = {
        responseError: function(response) {
            // Session has expired
            if (response.status == 419){
                var SessionService = $injector.get('SessionService');
                var $http = $injector.get('$http');
                var deferred = $q.defer();

                // Create a new session (recover the session)
                // We use login method that logs the user in using the current credentials and
                // returns a promise
                SessionService.login().then(deferred.resolve, deferred.reject);

                // When the session recovered, make the same backend call again and chain the request
                return deferred.promise.then(function() {
                    return $http(response.config);
                });
            }
            return $q.reject(response);
        }
    };
    return sessionRecoverer;
}])
.factory('fileReader', ["$q", "$log", function($q, $log){
	var onLoad = function(reader, deferred, scope) {
		return function () {
			scope.$apply(function () {
				deferred.resolve(reader.result);
			});
		};
	};
	var onError = function (reader, deferred, scope) {
		return function () {
			scope.$apply(function () {
				deferred.reject(reader.result);
			});
		};
	};
	var getReader = function(deferred, scope) {
		var reader = new FileReader();
		reader.onload = onLoad(reader, deferred, scope);
		reader.onerror = onError(reader, deferred, scope);
		return reader;
	};
	var readAsDataURL = function (file, scope) {
		var deferred = $q.defer();
		var reader = getReader(deferred, scope);
		reader.readAsDataURL(file);
		return deferred.promise;
	};
	return {
		readAsDataUrl: readAsDataURL
	};
}])
.config(function($httpProvider,$routeProvider) {

	//保存save数据后的响应
	$httpProvider.interceptors.push('saveAjax');	
	
	//控制器响应
	$httpProvider.interceptors.push('requestOverlay');
	
	



	//Session 恢复 (响应异常拦截器)
	$httpProvider.interceptors.push('sessionRecoverer');

	//拦截器，计算响应时间
	$httpProvider.interceptors.push('timestampMarker');

	//拦截器
	//$httpProvider.interceptors.push('ajaxInterceptor');

	/*
	//把Content-Type设置成x-www-form-urlencodedand
	//参考于国内网页http://m.oschina.net/blog/191640
	//上面又参考于国外网页http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	// Override $http service's default transformRequest
	$httpProvider.defaults.transformRequest = [function(data) {
		var param = function(obj) {
			var query = '';
			var name, value, fullSubName, subName, subValue, innerObj, i;

			for (name in obj) {
				value = obj[name];

				if (value instanceof Array) {
					for (i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value instanceof Object) {
					for (subName in value) {
						subValue = value[subName];
						fullSubName = name + '[' + subName + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value !== undefined && value !== null) {
					query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
				}
			}

			return query.length ? query.substr(0, query.length - 1) : query;
		};

		return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
	}];
	*/
});